﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace SharePointOfView.SPReporting
{
    public class Utilities
    {
        /// <summary>
        /// Activate the "Reports Center" feature on a web site
        /// </summary>
        /// <param name="web">SharePoint website</param>
        /// <returns>true is successfully activated</returns>
        public static bool ActivateReportsCenter(SPWeb web)
        {
            bool isActivated = false;

            try
            {
                web.Features.Add(Globals.SPReportingWebFeatureId);
                isActivated = true;
            }
            catch (Exception ex)
            {
                Debug.Write("Error : " + ex.Message, "SharePointOfView.SPReporting.Utilities.ActivateReportsCenter");
            }

            Debug.Write("Is Activated = " + isActivated + " on web " + web.Url, "SharePointOfView.SPReporting.Utilities.ActivateReportsCenter");

            return isActivated;
        }

        /// <summary>
        /// Deactivate the "Reports Center" feature on a web site
        /// </summary>
        /// <param name="web">SharePoint website</param>
        /// <returns>true is successfully deactivated</returns>
        public static bool DeactivateReportsCenter(SPWeb web)
        {
            bool isDeactivated = false;
            try
            {
                // Try to remove feature
                web.Features.Remove(Globals.SPReportingWebFeatureId);
                isDeactivated = true;
            }
            catch(Exception ex)
            {
                Debug.Write("Error : " + ex.Message, "SharePointOfView.SPReporting.Utilities.DeactivateReportsCenter");
            }

            Debug.Write("Is Deactivated = " + isDeactivated + " on web " + web.Url, "SharePointOfView.SPReporting.Utilities.DeactivateReportsCenter");

            return isDeactivated;
        }


        /// <summary>
        /// Deactivate the "SoV SPReporting" features from Reports Center and Farm
        /// </summary>
        /// <returns>true is successfully deactivated</returns>
        public static bool DeactivateSPReportingFeatures()
        {
            bool isDeactivated = false;

            if (!string.IsNullOrEmpty(ReportsCenterUrl))
            {
                using(SPSite site = new SPSite(ReportsCenterUrl))
                {
                    using(SPWeb web = site.OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;
                        List<Guid> featuresToRemove = new List<Guid>();
                        // Add feature to the list for further removal
                        foreach(SPFeature feature in web.Features)
                        {
                            // Check if the feature is a SoV SPReporting Feature
                            if (feature.Properties[Globals.IsSoVSPReportingFeaturePropertyName] != null)
                            {
                                featuresToRemove.Add(feature.DefinitionId);
                            }
                        }
                        // Remove tagged features (jobs)
                        foreach(Guid featureId in featuresToRemove)
                        {
                            web.Features.Remove(featureId);
                        }
                        // Remove web feature
                        DeactivateReportsCenter(web);
                        // Remove URL from properties
                        ReportsCenterUrl = null;

                        web.AllowUnsafeUpdates = false;

                        isDeactivated = true;
                    }
                }
            }

            Debug.Write("Is Deactivated = " + isDeactivated, "SharePointOfView.SPReporting.Utilities.DeactivateSPReportingFeatures");

            return isDeactivated;
        }

        /// <summary>
        /// Return Reports Center's Features
        /// </summary>
        /// <param name="language">Language used for culture and translations</param>
        /// <returns>A DataTable containing all informations about Reports Center's features</returns>
        public static DataTable GetReportsCenterFeatures(uint language)
        {
            CultureInfo ci = new CultureInfo((int)language);
            DataTable dtFeatures = new DataTable("Features");
            dtFeatures.Columns.Add("FeatureId", typeof(Guid));
            dtFeatures.Columns.Add("Title");
            dtFeatures.Columns.Add("Description");
            dtFeatures.Columns.Add("Status");
            dtFeatures.Columns.Add("StatusUI");
            dtFeatures.Columns.Add("ImageUrl");
            dtFeatures.Columns.Add("ImageAlt");
            dtFeatures.Columns.Add("ButtonText");

            foreach (SPFeatureDefinition featureDef in SPFarm.Local.FeatureDefinitions)
            {
                if (featureDef.Scope == SPFeatureScope.Web && featureDef.Properties[Globals.IsSoVSPReportingFeaturePropertyName] != null)
                {
                    DataRow dtRow = dtFeatures.NewRow();
                    dtRow["FeatureId"] = featureDef.Id;
                    dtRow["Title"] = featureDef.GetTitle(ci);
                    dtRow["Description"] = featureDef.GetDescription(ci);
                    dtRow["Status"] = "";
                    dtRow["StatusUI"] = "";
                    string featureImage = featureDef.GetImageUrl(ci);
                    dtRow["ImageUrl"] = string.IsNullOrEmpty(featureImage) ? Globals.DefaultFeatureImage : featureImage;
                    dtRow["ImageAlt"] = featureDef.GetImageAltText(ci);
                    dtRow["ButtonText"] = "Activate";

                    dtFeatures.Rows.Add(dtRow);
                }
            }

            if (!string.IsNullOrEmpty(ReportsCenterUrl))
            {
                using (SPSite site = new SPSite(ReportsCenterUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        for (int i = 0; i < dtFeatures.Rows.Count; i++)
                        {
                            Guid featureId = (Guid)dtFeatures.Rows[i]["FeatureId"];
                            if (web.Features[featureId] != null)
                            {
                                dtFeatures.Rows[i]["Status"] = "Active";
                                dtFeatures.Rows[i]["StatusUI"] = "Active";
                                dtFeatures.Rows[i]["ButtonText"] = "Deactivate";
                            }
                        }
                    }
                }
            }

            Debug.Write(dtFeatures.Rows.Count + " feature(s) found", "SharePointOfView.SPReporting.Utilities.GetReportsCenterFeatures");

            return dtFeatures;
        }

        #region Localization Helper
        public static string GetResourceString(string resourceKey)
        {
            uint language = SPContext.Current == null ? 0 : SPContext.Current.Web.Language;
            return GetResourceString(resourceKey, language);
        }

        public static string GetResourceString(string resourceKey, uint language)
        {
            return GetResourceString(resourceKey, Globals.DefaultResourceFilename, language);
        }

        public static string GetResourceString(string resourceKey, string resourceFile)
        {
            uint language = SPContext.Current == null ? 0 : SPContext.Current.Web.Language;
            return GetResourceString(resourceKey, resourceFile, language);
        }

        public static string GetResourceString(string resourceKey, string resourceFile, uint language)
        {
            return SharePointOfView.Utilities.Localization.GetResource(resourceKey, resourceFile, language);
        }
        #endregion

        #region Reports Center Configuration
        /// <summary>
        /// Returns true if the SPWeb is a "SoV Reports Center" enabled website
        /// </summary>
        /// <param name="web">A SharePoint Website</param>
        /// <returns></returns>
        public static bool IsReportsCenter(SPWeb web)
        {
            Debug.Write("Url = " + web.Url, "SharePointOfView.SPReporting.Utilities.IsReportsCenter");
            return web.Features[Globals.SPReportingWebFeatureId] != null;
        }

        private static string reportsCenterUrl = null;
        /// <summary>
        /// Reports Center Url Property
        /// </summary>
        public static string ReportsCenterUrl
        {
            get
            {
                string url = null;

                if (reportsCenterUrl == null)
                {
                    SPFeature feature = SPWebService.ContentService.Features[Globals.SPReportingFarmFeatureId];
                    if (feature != null)
                    {
                        SPFeatureProperty property = feature.Properties[Globals.ReportsCenterUrlFeaturePropertyName];
                        if (property != null)
                        {
                            reportsCenterUrl = property.Value;
                        }
                    }
                }

                url = reportsCenterUrl;

                Debug.Write(url, "SharePointOfView.SPReporting.Utilities.ReportsCenterUrl.Get");

                return url;
            }
            set
            {
                SPFeature feature = SPWebService.ContentService.Features[Globals.SPReportingFarmFeatureId];
                if (feature != null)
                {
                    SPFeatureProperty property = feature.Properties[Globals.ReportsCenterUrlFeaturePropertyName];
                    if (property != null)
                    {
                        property.Value = value;
                    }
                    else
                    {
                        property = new SPFeatureProperty(Globals.ReportsCenterUrlFeaturePropertyName, value);
                        feature.Properties.Add(property);
                    }
                    feature.Properties.Update();

                    reportsCenterUrl = value;

                    Debug.Write(reportsCenterUrl, "SharePointOfView.SPReporting.Utilities.ReportsCenterUrl.Set");
                }
            }
        }
        #endregion
    }
}
